import 'dart:async';
import 'dart:developer';

import 'package:flutter/services.dart';

import '../index.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<HomePage> {
  HomePageReport? _homePageReport;
  final PageData<Todo> _pageData = PageData();

  late StreamSubscription loginSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _handlerRefresh();
    loginSubscription = eventBus.on<OrderEvent>().listen((event) {
      Debug.info("刷新任务列表");
      _handlerRefresh(onlyRefreshList: true);
    });
  }

  @override
  void dispose() {
    super.dispose();
    //取消订阅
    loginSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    var darkModel = Provider.of<DarkModel>(context);
    // TODO: implement build
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            centerTitle: false,
            title: Text(
              "Hi，${Global.profile.user?.userName}",
            ),
            iconTheme: Theme.of(context).iconTheme,
            backgroundColor: Colors.transparent,
            systemOverlayStyle: darkModel.isDark(context)
                ? SystemUiOverlayStyle.light
                : SystemUiOverlayStyle.dark,
            actions: [
              // IconButton(
              //   onPressed: () {
              //     Navigator.pushNamed(context, "login");
              //   },
              //   icon: Icon(Icons.search),
              // )
            ],
          ),
          body: _buildBody(), // 构建主页面
        ),
      ),
    );
  }

  Widget _buildBody() {
    //开关灯时间
    UserConfigure? userConfigure = UserConfigureCache().getCurrentData();
    List<Permission>? list = userConfigure?.homeButtonList;
    // PermissionCache().getPermission("function")?.children;
    List<Widget> slivers = [];
    List<Permission> functionList = [];
    if (list != null) {
      for (Permission permission in list) {
        functionList.add(permission);
      }
    }
    String switchLightTime = _homePageReport?.switchLightTime?.value ?? "";
    List<String> strs = switchLightTime.split(" ");
    String openStr = "18:35";
    String closeStr = "06:35";
    for (String str in strs) {
      if (str.contains("开")) {
        openStr = str.substring(0, str.length - 1);
      } else if (str.contains("关")) {
        closeStr = str.substring(0, str.length - 1);
      }
    }
    ThemeData theme = Theme.of(context);
    TextStyle? textStyle = theme.textTheme.labelMedium
        ?.copyWith(color: theme.colorScheme.onSecondary);
    slivers.add(
      SliverToBoxAdapter(
        child: Container(
          height: 40,
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: Align(
            alignment: Alignment.centerLeft,
            child: RichText(
              text: TextSpan(
                children: [
                  WidgetSpan(
                    //对齐方式
                    alignment: PlaceholderAlignment.middle,
                    //这里就是中间显示的图片了也可以是其他任意的 Widget
                    child: Image.asset(
                      "images/home_hint.png",
                      width: 20,
                      height: 12,
                    ),
                  ),
                  TextSpan(
                    text: '今日计划开关灯时间：',
                    style: textStyle,
                  ),
                  WidgetSpan(
                    //对齐方式
                    alignment: PlaceholderAlignment.middle,
                    //这里就是中间显示的图片了也可以是其他任意的 Widget
                    child: Image.asset(
                      "images/home_open_light.png",
                      width: 20,
                      height: 12,
                    ),
                  ),
                  TextSpan(
                    text: openStr,
                    style: textStyle,
                  ),
                  WidgetSpan(
                    //对齐方式
                    alignment: PlaceholderAlignment.middle,
                    //这里就是中间显示的图片了也可以是其他任意的 Widget
                    child: Image.asset(
                      "images/home_close_light.png",
                      width: 20,
                      height: 12,
                    ),
                  ),
                  TextSpan(
                    text: closeStr,
                    style: textStyle,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );

    slivers.add(
      SliverToBoxAdapter(
          child: Container(
        margin: EdgeInsets.only(left: 16, right: 16),
        // height: 80,
        decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [
                Color(0xFF3B5EFD),
                Color(0xFF7D5BF2),
              ],
            ),
            borderRadius: BorderRadius.circular(3.3),
            boxShadow: [
              BoxShadow(
                  color: Color(0xFF0A8FFC),
                  offset: Offset(0.0, 1.6), //阴影xy轴偏移量
                  blurRadius: 6.0, //阴影模糊程度
                  spreadRadius: 0.33 //阴影扩散程度
                  )
            ]),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(
              width: 8,
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                    height: 20,
                  ),
                  Text(
                    _homePageReport?.alert?.value ?? "0",
                    style: Theme.of(context)
                        .textTheme
                        .titleLarge
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  Text(
                    "当前报警数",
                    style: Theme.of(context)
                        .textTheme
                        .labelMedium
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                ],
              ),
            ),
            const SizedBox(
              width: 8,
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                    height: 20,
                  ),
                  Text(
                    (_homePageReport?.lightingRate?.value ?? "0") + "%",
                    style: Theme.of(context)
                        .textTheme
                        .titleLarge
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  Text(
                    "当前亮灯率",
                    style: Theme.of(context)
                        .textTheme
                        .labelMedium
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                ],
              ),
            ),
            const SizedBox(
              width: 8,
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                    height: 20,
                  ),
                  Text(
                    _homePageReport?.produceOrders?.value ?? "0",
                    style: Theme.of(context)
                        .textTheme
                        .titleLarge
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  Text(
                    "现存工单数",
                    style: Theme.of(context)
                        .textTheme
                        .labelMedium
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                ],
              ),
            ),
            const SizedBox(
              width: 8,
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                    height: 20,
                  ),
                  Text(
                    _homePageReport?.pendingRate?.value ?? "0",
                    style: Theme.of(context)
                        .textTheme
                        .titleLarge
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  Text(
                    "待处理任务",
                    style: Theme.of(context)
                        .textTheme
                        .labelMedium
                        ?.copyWith(color: Colors.white),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                ],
              ),
            ),
            const SizedBox(
              width: 8,
            ),
          ],
        ),
      )),
    );

    if (functionList.isNotEmpty) {
      slivers.add(SliverPadding(
        padding: const EdgeInsets.all(2),
        sliver: SliverGrid(
          //Grid
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4, //Grid按两列显示
            mainAxisSpacing: 2.0,
            crossAxisSpacing: 2.0,
            childAspectRatio: 1.0,
          ),
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              Permission childPermission = functionList[index];
              //创建子widget
              return TextButton(
                  onPressed: () {
                    Debug.info("path：${childPermission.path}");
                    Navigator.of(context).pushNamed(childPermission.path!);
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 30,
                        height: 30,
                        child: (childPermission.imageUrl ?? "").isEmpty
                            ? Image.asset(
                                "images/avatar-default.png",
                                fit: BoxFit.cover,
                              )
                            : Image(
                                image: NetworkImage(childPermission.imageUrl!)),
                      ),
                      FittedBox(
                          child: Padding(
                        padding: EdgeInsets.only(top: 5),
                        child: Text(
                          childPermission.name,
                          style: Theme.of(context).textTheme.bodyMedium,
                        ),
                      ))
                    ],
                  ));
            },
            childCount: functionList.length,
          ),
        ),
      ));
    }
    slivers.add(SliverToBoxAdapter(
      child: InkWell(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(
              height: 50,
              width: 16,
            ),
            Expanded(
              child: Text(
                '我的待办',
                style: Theme.of(context).textTheme.titleMedium,
              ),
            ),
            const SizedBox(
              height: 40,
              width: 8,
            ),
            Text(
              '查看更多',
              textAlign: TextAlign.right,
              style: Theme.of(context).textTheme.labelLarge,
            ),
            const SizedBox(
              height: 40,
              width: 1,
            ),
            const Icon(Icons.chevron_right),
            const SizedBox(
              height: 40,
              width: 16,
            ),
          ],
        ),
        onTap: () => {Navigator.of(context).pushNamed("todo_list")},
      ),
    ));
    slivers.add(
      const SliverToBoxAdapter(
        child: Divider(
          height: 1,
        ),
      ),
    );
    slivers.add(
      SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, i) {
            final index = i ~/ 2;
            if (i.isOdd) {
              return const Divider(
                endIndent: 16,
                height: 1,
              );
            }
            if (_pageData.items.isEmpty) {
              return SizedBox(
                height: 300,
                child: HintWidget(
                  pageData: _pageData,
                ),
              );
            } else {
              return TodoItem(0, _pageData.items[index]);
            }
          },
          childCount:
              _pageData.items.isEmpty ? 1 : (_pageData.items.length * 2) - 1,
        ),
      ),
    );

    return EasyRefresh.custom(
        header: LightHeader(),
        footer: LightFooter(),
        onRefresh: () => _handlerRefresh(),
        slivers: slivers);
  }

  Future _handlerRefresh({bool onlyRefreshList = false}) async {
    try {
      _pageData.loadStatus = LoadStatus.loading;

      if (!onlyRefreshList) {
        ResponseData<HomePageReport> headResponseData =
            await Api(context).getHomePageReport();
        if (headResponseData.success) {
          if (mounted) {
            setState(() {
              _homePageReport = headResponseData.dataModel;
            });
          }
        }
      }

      ResponseData<RecordData<Todo>> responseData =
          await Api(context).getListTodo(queryParameters: {
        'current': PageData.initCurrent,
        'size': 5,
      }, refresh: true);
      if (responseData.success) {
        RecordData<Todo>? recordData = responseData.dataModel;
        List<Todo>? todoList = recordData?.recordModels;
        //如果返回的数据小于指定的条数，则表示没有更多数据，反之则否
        //把请求到的新数据添加到items中
        if (mounted) {
          setState(() {
            _pageData.loadStatus = LoadStatus.loadSuccess;
            _pageData.items.clear();
            if (todoList != null) {
              _pageData.items.addAll(todoList.map((e) => e));
            }
          });
        }
      } else {
        _pageData.hint = responseData.msg;
        //请求失败
        showToast(responseData.msg);
        setState(() {
          _pageData.loadStatus = LoadStatus.loadFail;
        });
      }
    } on DioError catch (e) {
      //失败则提示
      _pageData.hint = e.response?.statusMessage ?? S.of(context).networkError;
      _pageData.code = e.response?.statusCode;
      _pageData.errorType = e.type;
      if (_pageData.items.isNotEmpty) {
        showToast(e.response?.statusMessage ?? S.of(context).networkError);
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } on Error catch (e) {
      Debug.info("错误：" + e.toString());
      Debug.info(e.stackTrace.toString());

      //登录失败则提示
      _pageData.hint =
          Global.isRelease ? S.of(context).networkError : e.toString();
      if (_pageData.items.isNotEmpty) {
        showToast(Global.isRelease ? S.of(context).networkError : e.toString());
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } finally {}
  }
}
